using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
using WPF_MVVM_Test.MVVM_Model.Common;

namespace WPF_MVVM_Test.MVVM_Services
{
    public class HttpService
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        public HttpService()
        {
            _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri("http://8.140.242.140:8888/");
            _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
            };
        }

        public async Task<ApiResponse<T>> GetAsync<T>(string url)
        {
            try
            {
                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResponse<T>>(content, _jsonOptions);

                return result;
            }
            catch (HttpRequestException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"HTTP请求错误: {ex.Message}"
                };
            }
            catch (JsonException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"JSON解析错误: {ex.Message}"
                };
            }
            catch (Exception ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"未知错误: {ex.Message}"
                };
            }
        }

        public async Task<ApiResponse<T>> PostAsync<T>(string url, object data)
        {
            try
            {
                var json = JsonSerializer.Serialize(data, _jsonOptions);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 发送POST请求到: {url}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 请求内容: {json}");

                var response = await _httpClient.PostAsync(url, content);

                var responseContent = await response.Content.ReadAsStringAsync();
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 响应状态码: {response.StatusCode}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 响应内容: {responseContent}");

                if (!response.IsSuccessStatusCode)
                {
                    return new ApiResponse<T>
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"HTTP请求错误: Response status code does not indicate success: {(int)response.StatusCode} ({response.StatusCode}). Response: {responseContent}"
                    };
                }

                var result = JsonSerializer.Deserialize<ApiResponse<T>>(responseContent, _jsonOptions);
                return result ?? new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = "响应解析失败"
                };
            }
            catch (HttpRequestException ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] HTTP请求异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"HTTP请求错误: {ex.Message}"
                };
            }
            catch (JsonException ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] JSON序列化异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"JSON解析错误: {ex.Message}"
                };
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 未知异常: {ex.Message}");
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"未知错误: {ex.Message}"
                };
            }
        }

        public async Task<ApiResponse<T>> PutAsync<T>(string url, object data)
        {
            try
            {
                var json = JsonSerializer.Serialize(data, _jsonOptions);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PutAsync(url, content);
                response.EnsureSuccessStatusCode();

                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResponse<T>>(responseContent, _jsonOptions);

                return result;
            }
            catch (HttpRequestException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"HTTP请求错误: {ex.Message}"
                };
            }
            catch (JsonException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"JSON解析错误: {ex.Message}"
                };
            }
            catch (Exception ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"未知错误: {ex.Message}"
                };
            }
        }

        public async Task<ApiResponse<T>> DeleteAsync<T>(string url)
        {
            try
            {
                var response = await _httpClient.DeleteAsync(url);
                response.EnsureSuccessStatusCode();

                var content = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<ApiResponse<T>>(content, _jsonOptions);

                return result;
            }
            catch (HttpRequestException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"HTTP请求错误: {ex.Message}"
                };
            }
            catch (JsonException ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"JSON解析错误: {ex.Message}"
                };
            }
            catch (Exception ex)
            {
                return new ApiResponse<T>
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"未知错误: {ex.Message}"
                };
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}